from flask import Flask, jsonify, request, render_template
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.exc import IntegrityError
from datetime import datetime, timedelta

app = Flask(__name__)
# 修改为 MySQL 数据库连接字符串
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:password@localhost:3306/weather'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

# 天气数据表
class WeatherData(db.Model):
    __tablename__ = 'weather_data'
    id = db.Column(db.Integer, primary_key=True)
    location = db.Column(db.String(100), nullable=False)
    weather = db.Column(db.String(50))
    temperature = db.Column(db.String(20))
    humidity = db.Column(db.String(20))
    wind_direction = db.Column(db.String(20))
    wind_power = db.Column(db.String(20))
    forecast_date = db.Column(db.Date)
    record_time = db.Column(db.DateTime, default=datetime.utcnow)

    def to_dict(self):
        return {
            'location': self.location,
            'weather': self.weather,
            'temperature': self.temperature,
            'humidity': self.humidity,
            'wind_direction': self.wind_direction,
            'wind_power': self.wind_power,
            'forecast_date': self.forecast_date,
            'record_time': self.record_time
        }

# 测试数据
TEST_WEATHER_DATA = {
    "status": "1",
    "info": "OK",
    "lives": [
        {
            "weather": "晴",
            "temperature": "28",
            "humidity": "40%",
            "winddirection": "南风",
            "windpower": "3级",
            "reporttime": "2025-05-26 10:00:00"
        }
    ],
    "forecasts": [
        {
            "casts": [
                {
                    "dayweather": "晴",
                    "daytemp": "30",
                    "daywinddirection": "南风",
                    "daywindpower": "3级",
                    "date": "2025-05-26"
                },
                {
                    "dayweather": "多云",
                    "daytemp": "28",
                    "daywinddirection": "北风",
                    "daywindpower": "2级",
                    "date": "2025-05-27"
                }
            ]
        }
    ]
}

# 根据天气推荐穿搭
def recommend_clothing(weather, temperature):
    if "晴" in weather:
        if int(temperature) > 25:
            return "建议穿着短袖、短裤或裙子，注意防晒。"
        else:
            return "建议穿着长袖衬衫、薄外套，注意防晒。"
    elif "雨" in weather:
        return "建议携带雨具，穿着防水外套。"
    elif "雪" in weather:
        return "建议穿着厚外套、保暖衣物，注意防滑。"
    else:
        return "天气状况良好，适合外出，可根据个人喜好选择穿着。"

# 解析天气数据并存储到数据库
def save_weather_data(location, weather_data):
    try:
        # 解析实时天气数据
        live_weather = weather_data.get('lives', [])[0]  # 获取实时天气的第一个元素
        record = WeatherData(
            location=location,
            weather=live_weather.get('weather'),
            temperature=live_weather.get('temperature'),
            humidity=live_weather.get('humidity'),
            wind_direction=live_weather.get('winddirection'),
            wind_power=live_weather.get('windpower'),
            forecast_date=datetime.strptime(live_weather.get('reporttime'), '%Y-%m-%d %H:%M:%S').date()
        )
        db.session.add(record)

        # 解析天气预报数据
        forecasts = weather_data.get('forecasts', [])
        for forecast in forecasts[0].get('casts', []):  # 获取预报数据的第一个城市的预报列表
            forecast_record = WeatherData(
                location=location,
                weather=forecast.get('dayweather'),
                temperature=forecast.get('daytemp'),
                humidity=None,  # 预报数据中没有湿度信息
                wind_direction=forecast.get('daywinddirection'),
                wind_power=forecast.get('daywindpower'),
                forecast_date=datetime.strptime(forecast.get('date'), '%Y-%m-%d').date()
            )
            db.session.add(forecast_record)

        db.session.commit()
    except IntegrityError:
        db.session.rollback()
    except Exception as e:
        print(f"保存数据失败: {str(e)}")
        db.session.rollback()

# 缓存机制
weather_cache = {}
cache_expiry_time = timedelta(minutes=30)

# 提供天气数据接口
@app.route('/api/weather', methods=['GET'])
def get_weather():
    location = request.args.get('location')
    if not location:
        return jsonify({"error": "需要提供地点参数"}), 400

    # 检查缓存
    now = datetime.now()
    if location in weather_cache and (now - weather_cache[location]['timestamp'] < cache_expiry_time):
        return jsonify(weather_cache[location]['data'])

    # 获取天气数据（使用测试数据）
    weather_data = TEST_WEATHER_DATA

    # 解析并保存数据
    save_weather_data(location, weather_data)

    # 更新缓存
    weather_cache[location] = {
        'data': weather_data,
        'timestamp': now
    }

    # 添加穿搭建议
    live_weather = weather_data.get('lives', [])[0]
    clothing_recommendation = recommend_clothing(live_weather.get('weather'), live_weather.get('temperature'))
    weather_data['clothing_recommendation'] = clothing_recommendation

    return jsonify(weather_data)

# 查询历史天气数据接口
@app.route('/api/history_weather', methods=['GET'])
def get_history_weather():
    location = request.args.get('location')
    if not location:
        return jsonify({"error": "需要提供地点参数"}), 400

    try:
        history_data = WeatherData.query.filter_by(location=location).order_by(WeatherData.forecast_date.desc()).all()
        return jsonify([data.to_dict() for data in history_data])
    except Exception as e:
        return jsonify({"error": str(e)}), 500

# 前端页面
@app.route('/')
def index():
    return render_template('index.html')

if __name__ == '__main__':
    with app.app_context():
        db.create_all()
    app.run(host='0.0.0.0', port=5000, debug=True)